import { type Directive, type DirectiveBinding } from 'vue'

/**
 * 自定义指令：根据显示信息是否超出显示省略号动态添加title
 * 行数不传默认为 1
 */
export const ellipsis: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const rowNum: number = Number(binding.value)
    el.style.overflow = 'hidden'
    if (rowNum) {
      el.style.display = '-webkit-box'
      el.style.webkitLineClamp = String(rowNum)
      el.style.webkitBoxOrient = 'vertical'
      if (el.clientHeight - 20 < el.scrollHeight) {
        el.title = el.innerText
      }
    } else {
      el.style.textOverflow = 'ellipsis'
      el.style.whiteSpace = 'nowrap'
      if (el.clientWidth - 20 < el.scrollWidth) {
        el.title = el.innerText
      }
    }
  }
}
